<!DOCTYPE html>
<html>
<head>
<title>Parser Asynchronous Widget Creation Unit Test</title>
<style type="text/css">
	@import "../../resources/dojo.css";
</style>
<script type="text/javascript" src="../../dojo.js" data-dojo-config="isDebug:true, async:true"></script>
<script type="text/javascript">

require([
	"doh",
	"dojo/_base/array", "dojo/_base/declare", "dojo/Deferred", "dojo/dom", "dojo/_base/lang", "dojo/parser",
	"dojo/domReady!"
], function(doh, array, declare, Deferred, dom, lang, parser){

	// instances of AsyncWidget will finish initializing when this Deferred is resolved
	var finishCreatingAsyncWidgets = new Deferred();

	AsyncWidget = declare(null, {
		declaredClass: "AsyncWidget",
		markupFactory: function(params, node){
			// the markup factory can return a promise, and the parser will wait
			return finishCreatingAsyncWidgets.then(function(){return new AsyncWidget(params, node); });
		},
		constructor: function(args, node){
			this.params = args;
			lang.mixin(this, args);
		},
		startup: function(){
			this._started = true;
		}
	});

	SyncWidget = declare(null, {
		declaredClass: "SyncWidget",
		constructor: function(args, node){
			this.params = args;
			lang.mixin(this, args);
		},
		startup: function(){
			this._started = true;
		}
	});

	doh.register("async tests", [
		function parse(){
			var d = new doh.Deferred();

			// Call the parser
			var parsePromise = parser.parse(dom.byId("main"));
			
			// Parse should be waiting for the async widget to finish creating
			doh.f(parsePromise.isFulfilled(), "parse not finished yet");
			doh.is("undefined", typeof asyncWidget, "async widget not created yet");
			doh.f(syncWidget._started, "sync widget created by not started");

			// Now make the async widget finish initializing
			finishCreatingAsyncWidgets.resolve(true);

			parsePromise.then(d.getTestCallback(function(list){
				doh.t(asyncWidget._started, "async widget started");
				doh.t(syncWidget._started, "sync widget started too");
				doh.is("AsyncWidget, SyncWidget", array.map(list, function(cls){ return cls.declaredClass; }).join(", "),
						"list of instances returned from parser");
			}));

			return d;
		}
	]);

	doh.run();
});
</script>
</head>
<body>
<h1>Parser Asynchronous Widget Creation Unit Test</h1>

<div id=main>
	<span data-dojo-id="asyncWidget" data-dojo-type="AsyncWidget">hi</span>
	<span data-dojo-id="syncWidget" data-dojo-type="SyncWidget">there</span>
</div>

</body>
</html>
